<template>
    <view class="page">
        <!-- 答题组件使用swiper轮播组件开发，可以支持左右滑动选题功能。 -->
        <swiper class="question_swiper" :current="current" @change="handleSwiperChange" :indicator-dots="false" :autoplay="false" :interval="3000" :duration="1000">
            <swiper-item v-for="(item, index) in questions" :key="item.id">
                <view>
                    <!-- 题干部分 -->
                    <view class="question_item_name">
                        <text v-if="item.type === '1'" :class="'question_item_type_' + item.type">单选题</text>
                        <text v-if="item.type === '2'" :class="'question_item_type_' + item.type">多选题</text>
                        <text v-if="item.type === '3'" :class="'question_item_type_' + item.type">判断题</text>
                        {{ index + 1 }}. {{ item.name }}
                    </view>

                    <!-- 选项部分 -->
                    <view v-for="(option, optionIndex) in item.options" 
                          :class="[ 'question_item_option', option.indexOf('(selected)') >= 0 ? 'select' : '' ]" 
                          @tap="handleAnswer(item, option)">
                        <view class="question_item_option_id">{{ optionIds[optionIndex] }}</view>
                        <view class="question_item_option_name">{{ option.replace('(selected)', '') }}</view>
                    </view>

                    <!-- 如果是多选，并且还未答此题则提供确认选择按钮 -->
                    <view v-if="item.type === '2' && !item.answered" class="question_item_button" @tap="handleSubmit(item)">
                        提交选择
                    </view>
                </view>
            </swiper-item>
        </swiper>

        <!-- 底部操作栏 -->
        <view class="question_bar">
            <view class="question_bar_icon_wrapper">
                <image @tap="handleCard" class="question_bar_icon" src="../../static/menu.svg" mode="aspectFill"></image>
            </view>

            <!-- 页码 -->
            <view class="question_bar_info">
                {{ current + 1 }} / {{ questions.length }}
            </view>
            
            <!-- 总得分展示 -->
            <button class="add-btn" @tap="resultShow">提交</button>
        </view>

        <!-- 隐藏的答题卡 -->
        <view v-if="cardVisible" class="question_card">
            <view v-for="(p, index) in questions" :class="'question_card_point' + (index === current ? ' current' : (p.answered ? (p.right ? ' card-right' : ' card-error') : ''))" @tap="handleJump(index)">
                {{ index + 1 }}
            </view>
        </view>
    </view>
</template>

<script>
import { loadCategoryById, loadQuestionByCategoryId, getQuestionOptions } from '../../service/api.js';

export default {
    data() {
        return {
            // 当前类别
            category: null,
            // 当前题目列表
            questions: [],
            // 当前是第几题
            current: 0,
            // 当前总得分
            totalScore: 0,
            // 答题卡可见性
            cardVisible: false,
            // 选项标识符
            optionIds: ['A', 'B', 'C', 'D'],
            // 为4个选项分别定义得分
            scores: [1, 2, 3, 4],
            // 新增一个标志，控制是否显示得分
            showScore: false
        };
    },
    async onLoad(props) {
        try {
            const category = await loadCategoryById(props.categoryId);
            this.category = category;
            uni.setNavigationBarTitle({
                title: this.category.name,
            });
            uni.setNavigationBarColor({
                backgroundColor: '#00a9ff'
            });

            const questions = await loadQuestionByCategoryId(props.categoryId);
            for (let question of questions) {
                const options = await getQuestionOptions(props.categoryId, question.id);
                question.options = options;
            }
            this.questions = questions;
        } catch (err) {
            console.error(err);
        }
    },
    methods: {
        handleJump(current) {
            this.current = current;
            this.cardVisible = false;
        },
        handleCard() {
            this.cardVisible = !this.cardVisible;
            console.log('打开答题卡');
        },
        handleSwiperChange(e) {
            const index = e.detail.current;
            this.current = index;
        },
        handleAnswer(question, option) {
            if (question.answered) return;
            question.selectedOptionId = option;
            question.answered = true;
            this.$set(this.questions, this.questions.indexOf(question), question);
            if (question.type === '1' || question.type === '3') {
                this.calculateScore(question, option);
            }
            for (let optIndex in question.options) {
                if (question.options[optIndex] === option) {
                    question.options[optIndex] = option + '(selected)';
                }
            }
        },
        resultShow() {
            if (this.allOptionsAnswered()) {
                this.calculateTotalScore();
                this.showScore = true;
                uni.navigateTo({
                    url: '/pages/result/result?id=' + this.totalScore + '&item=' + this.category.id
                });
            }
        },
        allOptionsAnswered() {
            for (let question of this.questions) {
                if (!question.answered) {
                    return false;
                }
            }
            return true;
        },
        calculateTotalScore() {
            let totalScore = 0;
            for (let question of this.questions) {
                totalScore += question.score || 0;
            }
            this.totalScore = totalScore;
        },
        calculateScore(question, option) {
            question.score = this.scores[question.options.indexOf(option)];
            console.log('您的得分为：' + question.score);
        },
        handleSubmit(question) {
            if (!question.selectedOptionId) {
                uni.showToast({
                    title: '请选择选项！',
                    icon: 'none'
                });
                return;
            }
            question.answered = true;
            question.right = question.answer === question.selectedOptionId;
            this.calculateTotalScore();
        },
        finishTest() {
            this.$router.push({ name: 'Score', params: { totalScore: this.totalScore } });
        }
    }
};
</script>
<style>
	.question_card{
		background: white;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 110rpx;
		height: 60vh;
		box-shadow: 0 0 80rpx 8rpx #0000003d;
		display: flex;
		flex-wrap: wrap;
		padding: 30rpx;
	}
	.question_card_point{
		width: 70rpx;
		height: 70rpx;
		border: 2rpx solid #000000a6;
		color: #000000a6;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		margin: 20rpx;
	}
/* 	.question_wrapper {
		background: #0000000d;
		min-height: 100vh;
	} */

	.question_swiper {
		min-height: 100vh;
	}

	.question_item_name {
		background: white;
		padding: 30rpx;
		min-height: 200rpx;
		font-size: 32rpx;
		color: #1d2342b0;
		letter-spacing: 1rpx;
		line-height: 50rpx;
	}

	.question_item_type_1 {
		background: #7496ff;
		color: white;
		padding: 6rpx 16rpx;
		font-size: 24rpx;
		margin-right: 20rpx;
		border-radius: 10rpx;
	}

	.question_item_type_2 {
		background: #ffa874;
		color: white;
		padding: 6rpx 16rpx;
		font-size: 24rpx;
		margin-right: 20rpx;
		border-radius: 10rpx;
	}

	.question_item_type_3 {
		background: #ff7474;
		color: white;
		padding: 6rpx 16rpx;
		font-size: 24rpx;
		margin-right: 20rpx;
		border-radius: 10rpx;
	}

	.question_item_option {
		background: white;
		margin: 30rpx 30rpx 0 30rpx;
		padding: 30rpx;
		font-size: 30rpx;
		border-radius: 10rpx;
		display: flex;
		align-items: center;
		border: 2rpx solid white;
	}

	.question_item_option_id {
		font-weight: bold;
	}

	.question_item_option_name {
		margin-left: 30rpx;
		color: #000000b3;
	}

	.question_item_button {
		background: #6296e8;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 60rpx 30rpx 30rpx 30rpx;
		padding: 26rpx;
		font-size: 30rpx;
		border-radius: 10rpx;
		color: white;
	}
	.question_bar_total_score { 
		color: #000000a3; 
		font-size: 28rpx; 
		flex: 1; 
		text-align: center;
	}

	.select {
		border: 2rpx solid #7f93ff;
	}

	.right {
		border: 2rpx solid #92df9a;
	}

	.error {
		border: 2rpx solid #fba1a1;
	}

	.question_item_parse {
		background: white;
		padding: 30rpx;
		margin: 30rpx;
		font-size: 28rpx;
		color: #000000ad;
	}

	.question_bar {
		position: fixed;
		left: 0;
		bottom: 0;
		right: 0;
		background: white;
		display: flex;
		align-items: center;
		padding: 40rpx;
		z-index: 9999;
	}

	.question_bar_icon_wrapper {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.question_bar_icon {
		width: 36rpx;
		height: 36rpx;
	}

	.question_bar_info {
		color: #000000a3;
		font-size: 28rpx;
	}
	.current{
		background: #3493f9e6;
		color: white;
		border: 2rpx solid #3493f9e6;
	}
	.card-right{
		background: #92df9a;
		color: white;
		border: 2rpx solid #92df9a;
	}
	.card-error{
		background: #fba1a1;
		color: white;
		border: 2rpx solid #fba1a1;
	}
</style>
